<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus" v-model:active-key="currentTab" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key && tab.key != 100">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <template v-if="currentTab != 100">
      <div class="search-w table-filter-form">
        <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getTableList">
          <template #headerLeft>
            <a-space>
              <a-button type="primary" size="medium" @click="receiveOrder(selectIds)" v-if="currentTab == 20 && $authPass('procurement.plan.receive')">接单</a-button>
            </a-space>
          </template>
          <template #tableBody>
            <span class="expand-all-btn" v-if="tableList.length" @click="changeExpandAll">
              <icon-plus v-show="!expandAll" />
              <icon-minus v-show="expandAll" />
            </span>
            <a-table class="table-singe-line show-border-table" ref="tableListref" row-key="id" :expandable="expandable" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :data="tableList" size="mini" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column data-index="sort" key="sort" :width="40" title="序号">
                  <template #cell="{ rowIndex }">
                    <p>{{ rowIndex + 1 }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="billNo" key="billNo" :width="140" title="单号">
                  <template #cell="{ record }">
                    <div class="flex-c">
                      <span class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</span>
                      <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                    </div>
                  </template>
                </a-table-column>
                <a-table-column data-index="num" key="num" :width="100" title="申购数量">
                  <template #cell="{ record }">
                    <p>{{ record.skuType }}skus,{{ record.planAmt }}件</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="companyName" key="companyName" :width="120" title="申购公司" />
                <a-table-column data-index="salesmanName" key="salesmanName" :width="70" title="申购人" />
                <a-table-column data-index="1" key="2" :width="120" title="收货仓">
                  <template #cell="{ record }">
                    <p> {{ record.warehouseName }}（{{ record.warehouseCode }}）</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="productType" key="productType" :width="80" title="采购类型">
                  <template #cell="{ record }">
                    <p>{{ record.productType == 1 ? '普货' : '打样' }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="purchaseOrgName" key="purchaseOrgName" :width="100" title="采购部门" />
                <a-table-column data-index="gmtExpectDelivery" key="gmtExpectDelivery" :width="100" title="期望交货日期">
                  <template #cell="{ record }">
                    <p> {{ $setTime(record.gmtExpectDelivery, 'YYYY-MM-DD') }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="gmtAudit" key="gmtAudit" :width="140" title="提交时间">
                  <template #cell="{ record }">
                    <p> {{ $setTime(record.gmtAudit) }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="remark" :width="140" key="remark" title="备注">
                  <template #cell="{ record }">
                    <TextLimit :val="record.remark" />
                  </template>
                </a-table-column>
                <a-table-column data-index="handle" key="handle" :width="100" title="操作">
                  <template #cell="{ record }">
                    <a-space>
                      <a-button type="text" v-if="record.status == 20 && $authPass('procurement.plan.receive')" size="mini" @click="receiveOrder([record.id])">接单</a-button>
                      <a-button type="text" size="mini" @click="toDetail(record)">详情</a-button>
                    </a-space>
                  </template>
                </a-table-column>
              </template>
              <template #expand-row="{ record }">
                <ul class="expand-w">
                  <li class="bill-item-w flex-c" v-for="(item, i) in record.billItems" :key="i">
                    <div class="bill-item sku-info flex-c">
                      <ImgPopover :src="item.productImg">
                        <template #con>
                          <a-image width="50" height="50" fit="contain" :src="item.productImg" />
                        </template>
                      </ImgPopover>
                      <div>
                        <div class="flex-c">
                          <span class="highlight cursor" @click="toDetailItem(item)">{{ item.sku }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="item.sku" />
                        </div>
                        <p>{{ getProductSpecs(item) }}</p>
                        <div class="urgent" v-show="item.urgent">急</div>
                      </div>
                    </div>
                    <div class="bill-item prop-info">
                      <template v-if="item.purchaseSpecsArr && item.purchaseSpecsArr.length">
                        <PurchasePropPopover :purchaseSpecsArr="item.purchaseSpecsArr" />
                      </template>
                    </div>
                    <div class="bill-item">
                      <p>申购数量：{{ item.planAmt }}</p>
                      <p>工费单价：￥{{ item.laborPriceType == 1 ? item.laborPrice : Number(item.laborRate || 0) * Number(item.productPrice || 0) }}</p>
                      <p>合计工费：￥{{ item.laborAmount }}</p>
                    </div>

                    <div class="bill-item label-info">
                      <div style="height: 34px">
                        <PurchaseLabelsPopover source="application" :labels="item.labels" :edit="false" :billInfo="item" :showNum="6" />
                      </div>
                      <TextLimit :val="'备注：' + item.remark" :rows="1" />
                    </div>
                  </li>
                </ul>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </template>
    <template v-else>
      <div class="table-gl-con img-w">
        <div class="flex-c" style="margin-bottom: 10px">
          <p>开启对外采购服务：</p>
          <a-popconfirm :content="`确定是否${outPurchase ? '关闭' : '开启'}采购服务`" @ok="changeOutPurchaseState" type="warning">
            <a-switch v-model="outPurchase" :beforeChange="handleChangeIntercept">
              <template #checked> 开 </template>
              <template #unchecked> 关 </template>
            </a-switch>
          </a-popconfirm>
          <p style="font-size: 12px; margin-left: 20px; color: #666">只有开启了对外采购服务，集团内其他子公司在创建申购单的时候就可以选择其作为采购服务商，协同采购。</p>
        </div>
        <a-image width="100%" fit="contain" :preview="false" src="https://cdn2.selleroa.com/saas/product/165779416873205761.png" />
      </div>
    </template>
  </div>
  <!-- 接单 -->
  <ReceiveOrder v-if="showReceiveDialog" :isShow="showReceiveDialog" :ids="currentIds" @closed="showReceiveDialog = false" @success="getListAndCount" />
  <!-- 申购单详情 -->
  <PurchaseApplicationDetail v-if="showDetail" :isShow="showDetail" source="purchaser" :currentId="currentData.id" @closed="showDetail = false" />
  <!-- 申购单明细详情 -->
  <PurchaseItemDetail v-if="showItemDetail" :isShow="showItemDetail" source="purchaser" :currentItem="currentData" @closed="showItemDetail = false" />
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import PurchaseApplicationDetail from '../components/purchaseApplicationDetail.vue'
  import PurchaseItemDetail from '../components/purchaseApplicationItemDetail.vue'
  import ReceiveOrder from '../components/receiveOrder.vue'
  import PurchaseLabelsPopover from '../components/purchaseLabelsPopover.vue'
  import { Message } from '@arco-design/web-vue'
  import { findCompanyListByOutPurchase, findPurchasePlanByPurchasePage, findPurchasePlanCountStatusByPurchase } from '@/api/purchaseApplication'
  import { getCurrentCompany, openCompanyOutPurchase } from '@/api/system'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'
  import PurchasePropPopover from '../components/purchasePropPopover.vue'

  onMounted(() => {
    getDeptList()
    getListAndCount()
    getCompanyList()
    getCompanyInfo()
  })

  const expandable = ref<any>({
    title: '',
    width: 30,
  })
  const tabsList = [
    { key: 20, title: '待接单' },
    { key: 30, title: '采购中' },
    { key: 40, title: '已完成' },
    { key: 100, title: '申购业务流程' },
  ]
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [{ label: '单号', value: 'billNos' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [{ label: 'SKU', value: 'skus' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'companyIds',
      label: '申购公司',
      value: ref(),
      type: 'select_multiple',
      width: 160,
      optionItems: [],
    },
    {
      key: 'productType',
      label: '采购类型',
      value: ref(),
      type: 'select',
      width: 110,
      optionItems: [
        { label: '普货', value: 1 },
        { label: '样品', value: 2 },
      ],
    },
    {
      key: 'purchaseDeptId',
      label: '采购部门',
      placeholder: '采购部门',
      value: ref(),
      type: 'cascader1',
      width: 140,
      optionItems: [],
      attrs: {
        checkStrictly: true,
        fieldNames: { value: 'id', label: 'deptName' },
        placeholder: '采购部门',
        formatLabel: (options: any) => {
          const labels = options.map((option: any) => option.deptName)
          return labels?.[labels.length - 1]
        },
      },
    },
    {
      type: 'keyword_date_range',
      key: 'gmtExpectDelivery',
      keyItems: [
        { label: '期望交货日期', value: 'gmtExpectDelivery' },
        { label: '提交时间', value: 'gmtAudit' },
      ],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 20,
  })
  const expandAll = ref(false)
  const currentTab = ref(20)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})
  const currentIds = ref<Array<string>>([])
  const showDetail = ref(false)
  const showReceiveDialog = ref(false)
  const showItemDetail = ref(false)
  const countMap = ref<any>({})
  const filterData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const tableListref = ref()
  const outPurchase = ref(false)

  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 获取当前租户信息
  async function getCompanyInfo() {
    const res: any = await getCurrentCompany()
    outPurchase.value = res?.data?.outPurchase ? true : false
  }
  async function changeOutPurchaseState() {
    const msg = outPurchase.value ? '已关闭' : '已开启'
    const res: any = await openCompanyOutPurchase()
    if (res) {
      Message.success(msg)
      getCompanyInfo()
    }
  }
  // 折叠展开全部
  function changeExpandAll() {
    expandAll.value = !expandAll.value
    tableListref.value.expandAll(expandAll.value)
  }
  // 切换状态
  function changeStatus(status: number | string) {
    if (status === 100) return
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    nextTick(() => {
      getTableList()
    })
  }
  // 集团内子公司
  async function getCompanyList() {
    const res: any = await findCompanyListByOutPurchase()
    let list = res?.data || []
    filterItem.value[2].optionItems = list.map((el: any) => {
      return {
        label: el.companyName,
        value: el.id,
      }
    })
  }
  // 获取所有部门列表
  async function getDeptList() {
    await useBaseData.getDeptList()
    filterItem.value[4].optionItems = useBaseData.deptList
  }
  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }

  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findPurchasePlanCountStatusByPurchase()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    tableListref.value.selectAll(false)
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findPurchasePlanByPurchasePage(params)
    tableLoading.value = false
    let list = res?.data?.records || []
    list.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
        item.purchaseSpecsArr = Object.values(purchaseSpecs)
      })
    })
    tableList.value = list
    total.value = res?.data?.total || 0
  }

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 打开接单
  function receiveOrder(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择申购单')
      return
    }
    currentIds.value = ids
    showReceiveDialog.value = true
  }

  // 查看申购单详情
  function toDetail(item: any) {
    currentData.value = item || {}
    showDetail.value = true
  }

  // 查看申购单明细详情
  function toDetailItem(item: any) {
    currentData.value = item || {}
    console.log(currentData.value)
    showItemDetail.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  :deep(.table-con) {
    position: relative;
  }
  .expand-all-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 14px;
    height: 14px;
    padding: 0;
    color: var(--color-text-2);
    font-size: 12px;
    line-height: 14px;
    background-color: var(--color-neutral-3);
    border: 1px solid transparent;
    border-radius: 2px;
    outline: none;
    cursor: pointer;
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    position: absolute;
    top: 18px;
    left: 22px;
    z-index: 100;
  }
  .expand-w {
    padding: 0 20px;
    .bill-item-w {
      padding: 5px 0;
      border-bottom: 1px dashed #ddd;
      &:last-child {
        border-bottom: none;
      }
      .arco-image {
        margin-right: 5px;
      }
      .bill-item {
        margin-right: 20px;
        width: 160px;
        flex-shrink: 0;
      }
      .sku-info {
        width: 220px;
      }
      .prop-info {
        width: 220px;
      }
      .label-info {
        width: 260px;
      }
    }

    .urgent {
      font-size: 12px;
      display: inline-block;
      background-color: red;
      color: #fff;
      width: 18px;
      border-radius: 50%;
      line-height: 18px;
      text-align: center;
      transform: scale(0.82);
    }
  }
  .img-w {
    padding: 10px 20px;
    overflow-y: auto;
  }
</style>
